package com.vishudha.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public abstract class AbstractVishudhaWorker<V> implements VishudhaWorker<V> {
	private ExecutorService es;
	private List<Future<V>> futures;

	public AbstractVishudhaWorker(int poolSize) {
		es = Executors.newFixedThreadPool(poolSize);
		futures = new ArrayList<Future<V>>();
	}

	public V call(Callable<V> callable) {
		addFuture(es.submit(callable));
		return null;
	}

	protected void addFuture(Future<V> future) {
		futures.add(future);
	}
	
	public void waitForCompletion(){
		try {
			for (Future<V> future : futures) {
				future.get();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	public void shutdownService() {
		es.shutdown();
	}
}
